﻿using Koakuma.Game.Characters;
using Koakuma.Game.ECS;
using Koakuma.Game.UI;
using System.Collections;
using System.Collections.Generic;
using TGame.UI;
using TMPro;
using UnityEngine;

public class DailyBenefitsUIMediator : UIMediator<DailyBenefitsUIView>
{
    private CharacterAttributeComponent attributeComponent;
    private bool detailAttributeInitialized;

    private float startTime; // 记录UI打开时的时间戳
    private bool isCounting; // 计时状态控制

    protected override void OnShow(object arg)
    {
        base.OnShow(arg);
        view.btnClose.onClick.AddListener(Close);
        //模块切换
        for (int i = 0; i < view.listKeys.Count; i++)
        {
            int index = i;
            view.listKeys[index].onClick.AddListener(() => { ModulesChange(index); });
        }
        // 初始化时间相关
        startTime = Time.time;
        isCounting = true;
        //累计在线奖励领取
        for (int i = 0; i < view.btnTimes.Count; i++)
        {
            int index = i;
            view.btnTimes[index].onClick.AddListener(() => { BtnsTimeChange(index); });
        }
    }

    protected override void OnHide()
    {
        // 停止计时
        isCounting = false;
        view.btnClose.onClick.AddListener(Close);
        base.OnHide();
    }

    //重写OnUpdate方法
    protected override void OnUpdate(float deltaTime)
    {
        base.OnUpdate(deltaTime);
        if (isCounting)
        {
            UpdateTimeDisplay();
        }
    }

    private void BtnsTimeChange(int index)
    {
        view.btnTimes[index].interactable = false;
        view.btnTimes[index].transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = "已领取";
    }

    // 时间显示方法
    private void UpdateTimeDisplay()
    {
        //float elapsedTime = Time.time - startTime;
        float elapsedTime = Time.time;
        view.textTime.text = FormatTime(elapsedTime);
        //开放奖励领取 测试 5 10 15 20s min
        //实际上 300s 1200s 3600s 7200s
        if (elapsedTime >= 5)
        {
            view.btnTimes[0].transform.gameObject.SetActive(true);
        }
        if (elapsedTime >= 10)
        {
            view.btnTimes[1].transform.gameObject.SetActive(true);
        }
        if (elapsedTime >= 15)
        {
            view.btnTimes[2].transform.gameObject.SetActive(true);
        }
        if (elapsedTime >= 20)
        {
            view.btnTimes[3].transform.gameObject.SetActive(true);
        }
    }

    // 时间格式化方法
    private string FormatTime(float seconds)
    {
        System.TimeSpan timeSpan = System.TimeSpan.FromSeconds(seconds);
        return string.Format("{0:D2}:{1:D2}:{2:D2}",
            timeSpan.Hours,
            timeSpan.Minutes,
            timeSpan.Seconds);
    }

    //模块切换方法
    private void ModulesChange(int index)
    {
        for (int i = 0; i < view.listModules.Count; i++)
        {
            view.listModules[i].SetActive(false);
        }
        view.listModules[index].SetActive(true);
    }
}
